package com.jzg.sys.common.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class StatelessAuthcFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String reqMethod = request.getMethod();
        if("OPTIONS".equals(reqMethod)){
            response.setStatus(200);
            return false;
        }
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            onLoginFail(servletResponse);
            return false;
        }else{
            try {
                //生成无状态 Token
                StatelessToken statelessToken = new StatelessToken(token);
                //委托给 Realm 进行登录
                getSubject(request, response).login(statelessToken);
            } catch (Exception e) {
                e.printStackTrace();
                //登录失败
                onLoginFail(response);
                return false;
            }
        }
        return true;
    }

    //登录失败时默认返回 401 状态码
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login error");
    }
}
